package com.learn.problem;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author : Yu.Tan
 * @date : 2023/2/6 15:32
 * @desc : **
 */
public class TestSumOne {

    static final class SumTask extends RecursiveTask<Integer>{
        public int start;
        public int end;

        public SumTask(int start,int end){
            this.start=start;
            this.end=end;
        }

        @Override
        protected Integer compute() {
            if (end-start<=1000){
                System.out.println(Thread.currentThread().getName()+"开始执行"+start+":"+end);
                int sum=0;
                for (int i = start; i <= end ; i++) {
                    sum+=i;
                }
                return sum;
            }
            SumTask sumTaskOne=new SumTask(start,(start+end)/2);
            SumTask sumTaskTwo=new SumTask((start+end)/2+1,end);
            sumTaskOne.fork();
            sumTaskTwo.fork();

            return sumTaskOne.join()+sumTaskTwo.join();
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long millis = System.currentTimeMillis();
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        SumTask sumTask = new SumTask(1, 100000000);
        forkJoinPool.submit(sumTask);
        System.out.println("耗时="+(System.currentTimeMillis()-millis)+" 结果="+ sumTask.get());

        long millis1 = System.currentTimeMillis();
        int sum = sum(1, 100000000);
        System.out.println("耗时="+(System.currentTimeMillis()-millis1)+" 结果="+ sum);
    }

    static int sum(int start,int end){
        int sum=0;
        for (int i = start; i <= end ; i++) {
            sum+=i;
        }
        return sum;
    }

}
